<?php
// +----------------------------------------------------------------------
// | Description: 客户
// +----------------------------------------------------------------------
// | Author:  Zl
// +----------------------------------------------------------------------
namespace app\crm\model;

use app\admin\model\SysModel;
use app\admin\model\User;
use app\common\traits\ActionRecordTrait;
use think\facade\Db;
use app\admin\model\Common;
use think\response\Json;
use think\Validate;
use app\crm\logic\WhereLogic;

use app\admin\controller\ApiCommon;
use app\crm\model\BalanceLog;
use app\crm\model\Setting;
use app\crm\model\SettingCategory;
use app\crm\model\Service;
use app\crm\model\ReturnVist;
use app\crm\model\ReturnVistT;
use app\crm\model\Customer as CustomerModel;
use app\crm\model\TransferShop;
use app\crm\model\CustomerConfig as CustomerConfigModel;
use app\crm\model\CustomerGrade as CustomerGradeModel;
use app\crm\model\ReserveandLost;
use Kingdee\Kingdee;

class CustomerLossModel extends Common
{
    use ActionRecordTrait;
    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'customer';

    /**
     * 列表
     * 会员在门诊和门店的消费合并，达到会员条件时，成为会员
     * 拥有数据权限:
     * 1. 门店看自己
     * 2. 后台看列表
     * @param  array $request 请求参数
     * --------------------------------------------------------------------------+
     * 目前存在的搜索条件
     * -+
     * $request                     搜索参数集
     * --+
     * page                      int       页码
     * limit                     int       每页的数据
     * create_time               string    客户录入的日期: ****-**-**
     * customer_name             string    客户的名称
     * sex                       int       性别: 0未知 1男 2女
     * source_id                 int       客户来源
     * effective_entry           int       进店标识: 0未知 1是 2否
     * membership_leve           int       会员等级
     * member_classification     int       客户分类
     * repair_progress           int       修复进展: 0未知 其他设置按照id
     * scar_id                   int       疤痕类型: 关联查询 -- customer_scar表
     * consumption               decimal   消费金额
     * consumption_type          int       搜索消费金额的范围: 1大于 2小于 3等于
     * age                       int       客户的年龄
     * --------------------------------------------------------------------------+
     * @return array
     */
    public function getDataList(array $request): array
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        $is_export = $request['is_export'] ?? 0;



        $qichu_time = strtotime('2022-01-01 00:00:00');


        // 流失预警-4 流失顾客-3
        $is_join_shop = $request['is_join_shop'] ?? 0;
        if($is_join_shop==4){
            $time1 = strtotime('-1 month');
            $time2 = strtotime('-4 month');
        }

        if($is_join_shop==3){
            $time1 = strtotime('-4 month');
            $time2 = '0';
        }


        // 优案且已经毕业的顾客
        $yx_where = [];
        // $my_where = [];

        array_push($yx_where,['graduation_type','=','1']);
        array_push($yx_where,['selection_results','in',[2,3]]);

        $yx_customer_list = Db::name('case')->where($yx_where)->column('distinct customer_id');

        // echo "<pre>";
        // print_r($yx_customer_list);
        // exit;

        $client_list = [];

        foreach ($yx_customer_list as $k => $v) {
            $where = [];

            array_push($where,['customer_id','=',$v]);

            $caseList = Db::name('case')->where($where)->column('id,customer_id,selection_results,tg_excellent_time,graduation_type,position_id,position_name');

            $anli_num = count($caseList);

            // echo "<pre>";
            // print_r($caseList);

            if($anli_num<2){
                array_push($client_list,$v);
            }else{
                $position_list=[];// 部位
                $max_time = 0;// 最新评选时间
                $graduation_type = 0;// 毕业状态
                $selection_results = 0;// 评选结果
                foreach ($caseList as $k1 => $v1) {
                    if(in_array($v1['position_id'],$position_list)){
                        // 该部位已经评选为优秀或者满意案例了
                    }else{
                        if($v1['selection_results']=='2' || $v1['selection_results']=='3'){
                            if($v1['graduation_type']=='1'){
                                // 优秀或者满意 且已经毕业
                                array_push($position_list,$v1['position_id']);
                            }else{
                                if($v1['tg_excellent_time']>$max_time){
                                    $max_time = $v1['tg_excellent_time'];
                                    $graduation_type = $v1['graduation_type'];
                                    $selection_results = $v1['selection_results'];
                                }
                            }
                        }else{
                            if($v1['tg_excellent_time']>$max_time){
                                $max_time = $v1['tg_excellent_time'];
                                $graduation_type = $v1['graduation_type'];
                                $selection_results = $v1['selection_results'];
                            }
                        }
                    }
                }

                if($max_time>$time1){
                    array_push($client_list,$v);
                }

            }

        }


        // 分页数据
        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

        $user_id = $request['user_id'];
        //实例化搜索工具
        $whereLogic  = new WhereLogic();

        //初始化设置搜索的店铺集
        $whereLogic  -> setWhereSearch($request);

        //疤痕搜索
        // $whereType              = array();
        // $whereType['scar_id']   = '=';
        // $whereLogic             -> setWhereType($whereType);
        // $where                  = $whereLogic -> getWhere($request,$whereType);
        $customerIds            = array();
        if (isset($request['scar_id'])) {
            $customerIds        = Db::name('customer_scar')->where('customer_setting_id_type','=',$request['scar_id'])->column('customer_id');
        }
        //实例化搜索数据集
        $addSearch                          = array();
        if ($customerIds) {
            $addSearch['id']                = $customerIds;
            $whereType['id']                = 'in';
        }


        if ($addSearch) {
            $whereLogic     -> setWhereSearch($addSearch,1);
        }

        $whereType                          = array();
        $whereLogic         -> setWhereSearch($addSearch,1);

        $whereType['customer_name']         = 'like';
        $whereType['member_classification'] = '=';
        $whereType['telephone']             = '=';
        $whereLogic  -> setWhereType($whereType);
        $where       = $whereLogic -> getWhere($request,$whereType);

        // 排除已经评选上优案且已经毕业的顾客
        array_push($where,['id','not in',$client_list]);
        array_push($where,['cj_time','>',$qichu_time]);
        array_push($where,['final_consumption','<',$time1]);
        array_push($where,['final_service','<',$time1]);

        if (isset($request['create_time']) && !empty($request['create_time'])) {
            // code...
            array_push($where,['create_time','>=',strtotime($request['create_time'].' 00:00:00')]);
            array_push($where,['create_time','<=',strtotime($request['create_time'].' 23:59:59')]);
        }

        if (!empty($customerIds)) {
            array_push($where,['id','in',$customerIds]);
        }

        if (isset($request['shop_id'])&&intval($request['shop_id'])>0) {
            // code...
            array_push($where,['shop_id','=',$request['shop_id']]);
        }

        //查询该员工的 查询权限和客户档案
		$userList = Db::name('admin_user')->alias('u')
                    ->join('shop_person s', 'u.shop_person_id=s.id', 'LEFT')
                    ->where('u.id','=',$user_id)
                    ->where('u.is_status','=',0)
                    ->column('u.type,u.structure_name,u.structure_id,u.shop_person_id,s.position_id');

        //判断客服 归属的 只能查看自己的客户档案
        if($userList[0]['type'] ==1  && $userList[0]['structure_id'] =='8' ){
        array_push($where,['operator','=',$user_id]);
        }
        //判断店面护理师 只能查看自己名下的 客户档案
        if($userList[0]['type'] ==3  && $userList[0]['position_id'] =='9' ){
        array_push($where,['nurse_id','=',$userList[0]['shop_person_id']]);
        }

        // 年龄搜索
        $sexmin = $request['agemin'] ?? '';
        if ($sexmin !== ''){
            array_push($where,['age','>=',$sexmin]);
        }
        $sexmax = $request['agemax'] ?? '';
        if ($sexmax !== ''){
            array_push($where,['age','<=',$sexmax]);
        }

        $last_kftime_start = $request['last_kftime_start'] ?? '';
        $last_kftime_start = empty($request['last_kftime_start']) ? 0 : strtotime($request['last_kftime_start']);
        if($last_kftime_start > 0){
            array_push($where,['last_kftime','>=',$last_kftime_start]);
        }
        $last_kftime_end = $request['last_kftime_end'] ?? '';
        $last_kftime_end = empty($request['last_kftime_end']) ? 0 : strtotime($request['last_kftime_end']);
        if($last_kftime_end > 0){
            array_push($where,['last_kftime','<=',$last_kftime_end]);
        }

        $shopIds = $request['shopIds'] ?? [];
        if($shopIds){
            array_push($where,['shop_id','in',$shopIds]);
        }

        $shop_id = $request['shop_id'] ?? [];
        if($shop_id){
            array_push($where,['shop_id','=',$shop_id]);
        }

        $shopIdmz=[73782775131388,73782774881835,73782775392774,73782775377728,73782775206631,73782775085647];

        array_push($where,['shop_id','not in',$shopIdmz]);

        array_push($where,['member_label','not like','%588%']);

        array_push($where,['member_label','not like','%589%']);

        // echo "<pre>";
        // print_r($where);
        // echo "</pre>";
        // exit;

        $where2 = $where;

        $dataCounts   = Db::name('customer')
                            ->where($where)
                            ->where(function ($query) use ($time1,$time2) {
                                $cj_where1 = [];
                                $cj_where2 = [];

                                array_push($cj_where1,['final_consumption','>',$time2]);
                                array_push($cj_where1,['final_consumption','<',$time1]);

                                array_push($cj_where2,['final_service','>',$time2]);
                                array_push($cj_where2,['final_service','<',$time1]);

                                $query->where(function ($query) use ($cj_where1){
                                    $query->where($cj_where1);
                                });
                                $query->whereOr(function ($query) use ($cj_where2){
                                    $query->where($cj_where2);
                                });

                            })
                            ->count();
// echo $dataCounts;
        $onlyDataCounts = $request['onlyDataCounts'] ?? 'no';
        if($onlyDataCounts == 'yes'){
            $data = [
                'dataCounts' => $dataCounts ?? 0,
            ];
            return $data;
            exit;
        }

// exit;

        if ($dataCounts) {
            $onlyList = $request['onlyList'] ?? 'no';

            if($onlyList == 'yes'){
                $field          = ['id'];
            }else{
                $field          = ['id', 'customer_name', 'sex','telephone', 'birthday', 'effective_entry', 'shop_id','source_id','effective_entry','status','create_time','first_time','second_time','member_classification','turn_status','age','membership_leve','nurse_id','repair_progress','consumption','new_join_shop_time','final_consumption','final_service','be_overdue_time','cj_time','cj_money','operator','last_kftime','difficulty_level'];
            }



            $orderby    = 'id DESC';
            if($is_export == 1){
                $list           = Db::name('customer')
                                    ->where($where)
                                    ->where(function ($query) use ($time1,$time2) {
                                        $cj_where1 = [];
                                        $cj_where2 = [];

                                        array_push($cj_where1,['final_consumption','>',$time2]);
                                        array_push($cj_where1,['final_consumption','<',$time1]);

                                        array_push($cj_where2,['final_service','>',$time2]);
                                        array_push($cj_where2,['final_service','<',$time1]);

                                        $query->where(function ($query) use ($cj_where1){
                                            $query->where($cj_where1);
                                        });
                                        $query->whereOr(function ($query) use ($cj_where2){
                                            $query->where($cj_where2);
                                        });

                                    })
                                    ->field($field)->order($orderby)
                                    ->select()->toArray();
            }else{
                $list           = Db::name('customer')
                                    ->where($where)
                                    ->where(function ($query) use ($time1,$time2) {
                                        $cj_where1 = [];
                                        $cj_where2 = [];

                                        array_push($cj_where1,['final_consumption','>',$time2]);
                                        array_push($cj_where1,['final_consumption','<',$time1]);

                                        array_push($cj_where2,['final_service','>',$time2]);
                                        array_push($cj_where2,['final_service','<',$time1]);

                                        $query->where(function ($query) use ($cj_where1){
                                            $query->where($cj_where1);
                                        });
                                        $query->whereOr(function ($query) use ($cj_where2){
                                            $query->where($cj_where2);
                                        });

                                    })
                                    ->field($field)->order($orderby)
                                    ->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])
                                    ->select()->toArray();
            }

            if($onlyList == 'yes'){
                $data = [
                    'dataCount' => $dataCounts,
                    'list' => $list ?? [],
                ];
                return $data;
                exit;
            }

            $shopId         = array_values(array_unique(array_column($list, 'shop_id')));
            $nurseId        = array_values(array_unique(array_column($list, 'nurse_id')));
            $operatorIds       = array_values(array_unique(array_column($list, 'operator')));
            //获取店铺数据
            $shopList       = Db::name('shop')->where('shop_id', 'in', $shopId)->column('shop_name,market_name', 'shop_id');
            //获取员工数据
            $personList     = Db::name('shop_person')->where('id', 'in', $nurseId)->column('name', 'id');
            //获取会员等级
            $gradeList      = Db::name('customer_grade')->column('name', 'id');
            $adminList      = Db::name('admin_user')->where('id', 'in', $operatorIds)->column('realname', 'id');
            //基础配置
            $settingList    = Db::name('setting')->column('name', 'id');
            $sexArr         = ['0' => '未知', '1' => '男', '2' => '女'];
            $EntryArr       = ['1' => '是', '2' => '否'];

            foreach($list as $key => $val){
                if ($val['birthday']) {
                    $setData            = array();
                    $setData['age']     = bcsub(date('Y'),date('Y',$val['birthday']),0);
                    $setData['id']      = $val['id'];
                    $saveAll[]          = $setData;
                    $list[$key]['age']  = $setData['age'];
                }
            }

            foreach ($list as $key => $val) {
                $list[$key]['sex']             = $sexArr[$val['sex']] ?? '未知';
                $list[$key]['effective_entry'] = $EntryArr[$val['effective_entry']] ?? '否';
                $list[$key]['shop_name']       = $shopList[$val['shop_id']]['shop_name'] ?? '';
                $list[$key]['market_name']       = $shopList[$val['shop_id']]['market_name'] ?? '';
                $list[$key]['birthday']        = $val['birthday'] ? date('Y-m-d', $val['birthday']) : '';
                $list[$key]['source_name']     = $settingList[$val['source_id']] ?? '';
                // 进店-进店时间-进店状态1未进店2已进店
                $list[$key]['create_time']      = $val['create_time']?date('Y-m-d H:i:s',$val['create_time']):'';
                $list[$key]['first_time']      = $val['first_time']?date('Y-m-d H:i',$val['first_time']):'';
                $list[$key]['new_join_shop_time']      = $list[$key]['first_time']; // 首次进店时间

                $list[$key]['second_time']      = $val['second_time']?date('Y-m-d H:i',$val['second_time']):'';
                $list[$key]['second_join_shop_time']      = $list[$key]['second_time']; // 二次进店时间

                $list[$key]['final_consumption'] = $val['final_consumption'] ? date('Y-m-d H:i',$val['final_consumption']) : '';
                $list[$key]['final_service'] = $val['final_service'] ? date('Y-m-d H:i',$val['final_service']) : '';
                $list[$key]['last_kftime'] = $val['last_kftime'] ? date('Y-m-d H:i',$val['last_kftime']) : '';

                $list[$key]['be_overdue_time'] = $val['be_overdue_time'] ? date('Y-m-d H:i',$val['be_overdue_time']) : '';
                $list[$key]['first_status']    = $val['first_time'] ? '1' : '2' ;
                // 会员分类-分类id-分类名称
                $list[$key]['class_name']      = $settingList[$val['member_classification']] ?? '';
                // 会员等级
                $list[$key]['grade_name']      = $gradeList[$val['membership_leve']] ?? '';
                // 负责人名称
                $list[$key]['nurse_name']      = $personList[$val['nurse_id']] ?? '';
                // 修复进展
                $list[$key]['progress_name']   = $settingList[$val['repair_progress']] ?? '';
                // 客户疤痕内容
                $whereLogic  -> setWhereType($whereType);
                $where       = $whereLogic -> getWhere($request,$whereType);
                $dataCount   = $this->where($where)->count();
                $scarList    = Db::name('customer_scar')
                             ->where('customer_id','=',$val['id'])
                             ->group('customer_setting_id_type')
                             ->select()->toArray();
                $scar_aggregate          = '';
                if ($scarList){
                    $typeIdArr           = array_column($scarList, 'customer_setting_id_type');
                    foreach ($typeIdArr as $typeK => $typeV){
                        $str = $settingList[$typeV] ?? '';
                        $scar_aggregate .= $str.',';
                    }
                }
                $list[$key]['scar_aggregate']        = $scar_aggregate;
                // 客户的名称
                $list[$key]['customer_service_name'] = $adminList[$val['operator']] ?? '';
                // 成交时间
                $list[$key]['cj_time'] = $val['cj_time'] ? date('Y-m-d H:i:s',$val['cj_time']) : '' ;
                $list[$key]['cj_money'] = $val['cj_money'];
                $list[$key]['customer_name_phone'] = $val['customer_name'].'/'.$val['telephone'];
            }
        }


        // 总数统计
        if($dataCounts > 0){
            $cjNum = $this->where($where2)->where('member_classification','=',73)
                                        ->where(function ($query) use ($time1,$time2) {
                                            $cj_where1 = [];
                                            $cj_where2 = [];

                                            array_push($cj_where1,['final_consumption','>',$time2]);
                                            array_push($cj_where1,['final_consumption','<',$time1]);

                                            array_push($cj_where2,['final_service','>',$time2]);
                                            array_push($cj_where2,['final_service','<',$time1]);

                                            $query->where(function ($query) use ($cj_where1){
                                                $query->where($cj_where1);
                                            });
                                            $query->whereOr(function ($query) use ($cj_where2){
                                                $query->where($cj_where2);
                                            });

                                        })->count() ?? 0;
            $yzNum = $this->where($where2)->where('member_classification','=',72)
                                        ->where(function ($query) use ($time1,$time2) {
                                            $cj_where1 = [];
                                            $cj_where2 = [];

                                            array_push($cj_where1,['final_consumption','>',$time2]);
                                            array_push($cj_where1,['final_consumption','<',$time1]);

                                            array_push($cj_where2,['final_service','>',$time2]);
                                            array_push($cj_where2,['final_service','<',$time1]);

                                            $query->where(function ($query) use ($cj_where1){
                                                $query->where($cj_where1);
                                            });
                                            $query->whereOr(function ($query) use ($cj_where2){
                                                $query->where($cj_where2);
                                            });

                                        })->count() ?? 0;
            $ptNum = $this->where($where2)->where('member_classification','=',71)
                                        ->where(function ($query) use ($time1,$time2) {
                                            $cj_where1 = [];
                                            $cj_where2 = [];

                                            array_push($cj_where1,['final_consumption','>',$time2]);
                                            array_push($cj_where1,['final_consumption','<',$time1]);

                                            array_push($cj_where2,['final_service','>',$time2]);
                                            array_push($cj_where2,['final_service','<',$time1]);

                                            $query->where(function ($query) use ($cj_where1){
                                                $query->where($cj_where1);
                                            });
                                            $query->whereOr(function ($query) use ($cj_where2){
                                                $query->where($cj_where2);
                                            });

                                        })->count() ?? 0;
            $zcNum = $this->where($where2)->where('member_classification','=',70)
                                        ->where(function ($query) use ($time1,$time2) {
                                            $cj_where1 = [];
                                            $cj_where2 = [];

                                            array_push($cj_where1,['final_consumption','>',$time2]);
                                            array_push($cj_where1,['final_consumption','<',$time1]);

                                            array_push($cj_where2,['final_service','>',$time2]);
                                            array_push($cj_where2,['final_service','<',$time1]);

                                            $query->where(function ($query) use ($cj_where1){
                                                $query->where($cj_where1);
                                            });
                                            $query->whereOr(function ($query) use ($cj_where2){
                                                $query->where($cj_where2);
                                            });

                                        })->count() ?? 0;
            $statisticsData = [
                    'allnum'=>$dataCounts,
                    'cj'=>[
                            'num'=>$cjNum,
                            'zhanbi'=>bcmul(bcdiv($cjNum,$dataCounts,2),100,2).'%'
                        ],
                    'yz'=>[
                            'num'=>$yzNum,
                            'zhanbi'=>bcmul(bcdiv($yzNum,$dataCounts,2),100,2).'%'
                        ],
                    'pt'=>[
                            'num'=>$ptNum,
                            'zhanbi'=>bcmul(bcdiv($ptNum,$dataCounts,2),100,2).'%'
                        ],
                    'zc'=>[
                            'num'=>$zcNum,
                            'zhanbi'=>bcmul(bcdiv($zcNum,$dataCounts,2),100,2).'%'
                        ],
                ];
        }else{
            $statisticsData = [
                'allnum'=>0,
                'cj'=>[
                        'num'=>0,
                        'zhanbi'=>'0%'
                    ],
                'yz'=>[
                        'num'=>0,
                        'zhanbi'=>'0%'
                    ],
                'pt'=>[
                        'num'=>0,
                        'zhanbi'=>'0%'
                    ],
                'zc'=>[
                        'num'=>0,
                        'zhanbi'=>'0%'
                    ],
            ];
        }

        /**总数统计**/
        $data              = [];
        $data['list']      = $list ?? [];
        $data['statisticsData'] = $statisticsData;
        $data['dataCount'] = $dataCounts ?? 0;
        // $data['request'] = $request;
        return $data;
    }

    public function getDataList1(array $request):array
    {

        $today = date('Y-m-d',time());

        $model = new ReserveandLost();

        $shopIds = $request['shopIds'];


        $is_join_shop = $request['is_join_shop'] ?? 0;

		/* 客户活跃度 --- 条件整理 */
		$spend = $request['spend'] ?? '';

        $nurse_id = $request['shop_person_id']??0;

        $sysModel = new SysModel();

        $position_id = $sysModel->getPersonPositionId($nurse_id);
        if(!empty($position_id)){
            $request['nurse_id'] = $nurse_id;
        }

        if($shopIds){


            if($is_join_shop != 9){

                $cj_customerIds = $model->cj_customer($shopIds,$request);

            }


        }else{

            if($is_join_shop != 9){

                $shop_where = [];

                array_push($shop_where,['shop_type','=','2']);

                array_push($shop_where,['type','<>','2']);

                array_push($shop_where,['status','=','1']);

                $shopIds = Db::name('shop')->where($shop_where)->column('shop_id');

                $cj_customerIds = $model->cj_customer($shopIds,$request);

            }

        }

        $res_customerIds = $cj_customerIds;



        // 流失预警-4
        if($is_join_shop==4){

            $type = $request['type'] ?? '';

            $shop_id = $request['shop_id'] ?? '';

            $shop_ids = [];

            if($shop_id){

                array_push($shop_ids,$shop_id);

            }

            $start_time = $request['start_time'] ?? '';

            $res_customerIds = $model->warning_customer($cj_customerIds,$today,$type,$shop_ids,$start_time);

        }

        // 流失顾客-3
        if($is_join_shop==3){

            $res_customerIds = $model->lost_customer($cj_customerIds,$today);

        }

        $member_classification = $request['member_classification'] ?? '';



        // 保有顾客
        if($is_join_shop==8 || $member_classification ){


            $res_customerIds = $model->baoyou_customer($cj_customerIds,$today);


        }

		/* 客户活跃度--具体查询流程 */

		$start_time = strtotime(date('Y') . '-01-01');  //当年第一天
		$end_time = strtotime(date('Y') . '-12-31') + 86399;

		$new_customerId1 =[];
		$new_customerId2 =[];
		$new_customerId3 =[];
		$i = 0;
		$j = 0;
		$a = 0;
		if($spend){

			// 根据客户ID查询 收款单金额

			foreach ($res_customerIds as $key => $val) {


				$customerlistSK =Db::name('shop_refund_order')
				    ->where('deal_time','>=',$start_time)
				    ->where('deal_time','<=',$end_time)
				    ->where('uid','=',$val)
					->where('type','=',3)
				    ->where('status','=',2)
					->where('refund_type','<>',101.03)
				    ->column('sum(pay_amount) as count,uid');


				$customerlistTK =Db::name('shop_refund_order')
				    ->where('deal_time','>=',$start_time)
				    ->where('deal_time','<=',$end_time)
				    ->where('uid','=',$val)
					->where('type','=',1)
				    ->where('status','=',2)
					->where('refund_type','<>',101.03)
				    ->column('sum(pay_amount) as count,uid');

				//收款单金额合计  减去 退款单金额合计

				$customerAmount = bcsub($customerlistSK[0]['count'],$customerlistTK[0]['count'],2);

				/* 客户年度消费金额 小于 30000  */
				if($customerAmount < 30000){

					$new_customerId1[$i]['id'] = $val;
					$i++;
				}

				/* 客户年度消费金额 大于等于 30000  小于 50000 */
				if($customerAmount >= 30000 && $customerAmount < 50000){
					$new_customerId2[$j]['id'] = $val;
					$j++;
				}
				/* 客户年度消费金额 大于等于 50000  */
				if($customerAmount >= 50000){

					$new_customerId3[$a]['id'] = $val;
					$a++;
				}

			}
			if($spend  == 1){
				$cids_tt= array_values(array_unique(array_column($new_customerId1, 'id')));
			}

			if($spend  == 2){
				$cids_tt= array_values(array_unique(array_column($new_customerId2, 'id')));
			}

			if($spend  == 3){
				$cids_tt= array_values(array_unique(array_column($new_customerId3, 'id')));
			}

			$res_customerIds = $cids_tt;
		}



        // 预警回流
        if($is_join_shop==9){ //

            // echo "<pre>";
            // print_r($request);
            // echo "</pre>";
            // exit;

            $where = [];

            $tag_time = date('Ym01',time());

            $begin_time = date('Y-m-01',time());

            $over_time = time();

            $warn_time = $request['warn_time'] ?? '';

            $back_time = $request['back_time'] ?? '';

            $shop_id = $request['shop_id'] ?? '';

            if($warn_time){

                $tag_time = date('Ymd',strtotime($warn_time));

                $begin_time = $warn_time;

            }

            if($back_time){

                $over_time = strtotime($back_time);

            }

            // $tag_time = '20230327';

            // $begin_time = '2023-03-27';



            array_push($where,['date','=',$tag_time]);

            if($shopIds){

                array_push($where,['shop_id','in',$shopIds]);

            }

            if($shop_id){

                array_push($where,['shop_id','=',$shop_id]);

            }

            // echo "<pre>";
            // print_r($where);
            // echo "</pre>";
            // exit;

            $warn_customerIds = Db::name('customer_tj')->where($where)->column('warn_customer_ids');

            $warn_customer_ids = implode(',',$warn_customerIds);
            $warn_customer_arr = explode(',',$warn_customer_ids);

            // echo "<pre>";
            // print_r($warn_customer_arr);
            // echo "</pre>";
            // exit;


            $res_customerIds = $model->back_customer($warn_customer_arr,$begin_time,$over_time);

            // echo "<pre>";
            // print_r($res_customerIds);
            // echo "</pre>";

            // echo "预警回流";exit;

        }

        $is_export = $request['is_export'] ?? 0;
        // 分页数据
        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 10;

        $where = [];

        array_push($where,['c.id','in',$res_customerIds]);

        $scar_type_id =$request['scar_type_id']??0;

        if(in_array($scar_type_id,[1,2,3])){
            switch ($scar_type_id){
                case 1:
                    array_push($where,['cs.customer_setting_id_type','in',[1,2,3,4,5,6,7,8,655,656]]);
                    break;
                case 2:
                    array_push($where,['cs.customer_setting_id_type','=',10]);
                    break;
                case 3:
                    array_push($where,['cs.customer_setting_id_type','in',[9,11,12]]);
                    break;
            }
        }

        $orderby = 'c.id DESC';

		$scar_type_id =$request['scar_type_id']??0;

		if(in_array($scar_type_id,[1,2,3])){
		    switch ($scar_type_id){
		        case 1:
		            array_push($where,['cs.customer_setting_id_type','in',[1,2,3,4,5,6,7,8,655,656]]);
		            break;
		        case 2:
		            array_push($where,['cs.customer_setting_id_type','=',10]);
		            break;
		        case 3:
		            array_push($where,['cs.customer_setting_id_type','in',[9,11,12]]);
		            break;
		    }
		}

        $field = ['c.id', 'c.customer_name', 'c.sex','c.telephone', 'c.birthday', 'c.effective_entry', 'c.shop_id','c.source_id','c.effective_entry','c.status','c.create_time','c.first_time','c.second_time','c.member_classification','c.turn_status','c.age','c.membership_leve','c.nurse_id','c.repair_progress','c.consumption','c.new_join_shop_time','c.final_consumption','c.final_service','c.be_overdue_time','c.cj_time','c.cj_money','c.operator','c.last_kftime','c.difficulty_level','cs.customer_setting_id_type'];

        if($is_export == 1){

            $listY = Db::name('customer')->alias('c')
                    ->join('customer_scar cs', 'c.id=cs.customer_id', 'LEFT')
                    ->where($where)
                    ->field($field)->order($orderby)
                    ->group('c.id')
                    ->select()
                    ->toArray();
            $listYCount = count($listY);

        }else{


            $listYCount = Db::name('customer')->alias('c')
                        ->join('customer_scar cs', 'c.id=cs.customer_id', 'LEFT')
                        ->where($where)
                        ->field($field)
                        ->group('c.id')
                        ->count();


            $listY =[];
            if($listYCount>0){
                 $listY = Db::name('customer')->alias('c')
                        ->join('customer_scar cs', 'c.id=cs.customer_id', 'LEFT')
                        ->where($where)
                        ->field($field)->order($orderby)
                        ->group('c.id')
                        ->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])
                        ->select()
                        ->toArray();
            }


            // print_r($listY);die;
        }


        // echo "<pre>";
        // print_r($listY);
        // echo "</pre>";
        // exit;

        $type = $request['type'] ?? "";

        if($type == 'liushiyj' || $type == 'liushikh' ){

            return $cids = array_values(array_unique(array_column($listY, 'id')));

            exit;

        }


        // 获取门店id
        $shop_ids = array_values(array_unique(array_column($listY, 'shop_id')));

        $where = [];

        array_push($where,['shop_id','in',$shop_ids]);

        $shop_names = Db::name('shop')->where($where)->column('shop_name','shop_id');

        // 获取来源id
        $source_ids = array_values(array_unique(array_column($listY, 'source_id')));

        $where = [];

        array_push($where,['id','in',$source_ids]);

        $source_names = Db::name('setting')->where($where)->column('name','id');

        // 获取护理师id
        $nurse_ids = array_values(array_unique(array_column($listY, 'nurse_id')));

        $where = [];

        array_push($where,['id','in',$nurse_ids]);

        //获取员工数据
        $personList = Db::name('shop_person')->where($where)->column('name', 'id');

        //获取会员等级
        $gradeList = Db::name('customer_grade')->column('name', 'id');

        // 获取疤痕类型
        $scarType = Db::name('setting')->where('category_id','=','1')->column('name','id');

        //基础配置
        $settingList    = Db::name('setting')->column('name', 'id');
        $sexArr         = ['0' => '未知', '1' => '男', '2' => '女'];
        $EntryArr       = ['1' => '是', '2' => '否'];



        $list = [];

        foreach ($listY as $key => $val) {

            $one = [];

            $one['id'] = $val['id'];

            $one['cj_time'] = $val['cj_time']?date('Y-m-d',$val['cj_time']):'';

            $one['customer_name'] = $val['customer_name'] ?? '';

            $one['telephone'] = $val['telephone'] ?? '';

            $one['last_kftime'] = $val['last_kftime']?date('Y-m-d',$val['last_kftime']):'';

            $one['sex'] = $val['sex'] == 1 ? '男':'女';

            $one['age'] = $val['age'] ?? '';

            $one['new_join_shop_time'] = $val['second_time']?date('Y-m-d',$val['second_time']):($val['first_time']?date('Y-m-d',$val['first_time']) : "");

            $one['source_name'] = $source_names[$val['source_id']] ?? "";

            $one['grade_name'] = $gradeList[$val['membership_leve']] ?? "";

            $one['nurse_name'] = $personList[$val['nurse_id']] ?? "";

            $one['shop_name'] = $shop_names[$val['shop_id']] ?? "";

            $one['class_name'] = $settingList[$val['member_classification']] ?? "";

            $one['final_consumption'] = $val['final_consumption']?date('Y-m-d',$val['final_consumption']):'';

            $one['final_service'] = $val['final_service']?date('Y-m-d',$val['final_service']):'';

            $one['consumption'] = $val['consumption'] ?? '';

            $scarIds = explode(',',$val['customer_setting_id_type']);

            $scarName = [];

            foreach ($scarIds as $key1 => $value1) {

                $onename = $scarType[$value1] ?? '未知';

                array_push($scarName,$onename);

            }

            $one['scar_aggregate'] = implode($scarName) ?? "";

            array_push($list,$one);

        }

        // echo "<pre>";
        // print_r($list);
        // echo "</pre>";
        // exit;

        $data              = [];
        $data['list']      = $list ?? [];
        $data['statisticsData'] = [];
        $data['dataCount'] = $listYCount;

        // echo "<pre>";
        // print_r($data);
        // echo "</pre>";
        // exit;
        return $data;

    }

}
